package beer.coder.walawala.gui.component;

import java.util.Timer;
import java.util.TimerTask;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

/**
 * TODO
 *
 * @author amath0312
 * @version 1.0
 * @date 2019-12-21 23:01
 */
public class Toast {

  private static Stage stage = new Stage();
  private static Label label = new Label();

  static {
    stage.initStyle(StageStyle.TRANSPARENT);
  }

  //默认3秒
  public static void toast(String msg, Stage parent) {
    toast(msg, 3000, parent);
  }

  /**
   * 指定时间消失
   */
  public static void toast(String msg, int time, Stage parent) {
    stage.initOwner(parent);
    label.setText(msg);
    TimerTask task = new TimerTask() {
      @Override
      public void run() {
        Platform.runLater(() -> stage.close());
      }
    };
    init(msg);
    Timer timer = new Timer();
    timer.schedule(task, time);

    stage.show();
    if (parent != null) {
      double x = parent.getX() + (parent.getWidth() - stage.getWidth()) / 2.0;
      stage.setX(x);

      double y = parent.getY() + parent.getHeight() - 60;
      stage.setY(y);
    }
  }

  //设置消息
  private static void init(String msg) {
    Label label = new Label(msg);//默认信息
    label.setStyle("-fx-background: rgba(56,56,56,0.7);-fx-border-radius: 25;-fx-background-radius: 15");
    label.setTextFill(Color.rgb(225, 255, 226));//消息字体颜色
    label.setPrefHeight(50);
    label.setPadding(new Insets(15));
    label.setAlignment(Pos.CENTER);//居中
    label.setFont(new Font(16));//字体大小
    Scene scene = new Scene(label);
    scene.setFill(null);//场景透明

    stage.setScene(scene);
    stage.setAlwaysOnTop(true);
  }
}
